package com.server.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.server.common.base.PathManager;
import com.server.common.base.SessionData;
import com.server.common.util.ExportExcelUtil;
import com.server.common.util.ImportExcelUtil;
import com.server.service.IOrgManagementService;
import com.server.service.IUserManagementService;
import com.server.web.GridFilterFormatter;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;

@Controller
@RequestMapping("excel")
public class ExcelController {
	
	@Autowired
	private IUserManagementService userManagementService;
	@Autowired
	private IOrgManagementService orgManagementService;
	
	/*@Autowired
	private ISignUpService signUpService;
	@Autowired
	private IRegisterService registerService;*/


	@RequestMapping("import")
	public void importExcel(HttpServletRequest request,HttpServletResponse response){
		String operator = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		
		String filePath = request.getParameter("filePath");
		//1.获取绝对路径
		String realPath = PathManager.FILE_BASEPATH+filePath;
		
		//2.excel文件抽取数据生成List<Map>
		List<Map<String, Object>> file2List = ImportExcelUtil.file2List(realPath, 0);
		
		//3.入职
		Map<String, Object> infor = userManagementService.addAndEmployBatch(operator, file2List);
		
		OutputUtil.returnString(response, JSONSerielizer.toJson(infor, null, null));
	}
	/**
	 * 员工资料导出
	 * @param request
	 * @param response
	 * @param orgNo 
	 * @param fileName
	 * @throws IOException
	 * @author ServerZhang
	 * @date 2017年5月11日
	 */
	@RequestMapping("export/user/{orgNo}/{fileName}/{filterdata}")
	public void export(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String orgNo,
			@PathVariable String fileName,@PathVariable String filterdata) throws IOException {
		
		String whereStr = GridFilterFormatter.format(filterdata);
		
		String operator = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		Integer level = SessionUtil.getIntAttri(request, SessionData.levelKey);
		
		if ("all".equals(orgNo)) {
			orgNo = null;
		}
		if (level < 9) {
			orgNo = orgManagementService.getOrg4User(operator);
		}
		

		Boolean isSuccess = true;
		List<Map<String, Object>> list = userManagementService.getList(orgNo, 1, whereStr);
		
	//	Map<String, Object> userMap = registerService.read(phoneNo);
		for (int i = 0; i < list.size(); i++) {
			if ( list.get(i).get("Sex").toString().equals("1") ) {
				list.get(i).put("Sex", "男");
			}else{
				list.get(i).put("Sex", "女");
			}
			if ( list.get(i).get("Nature").toString().equals("1") ) {
				list.get(i).put("Nature", "长期");
			}else{
				list.get(i).put("Nature", "短期");
			}
		}
		String sheetName = "员工资料";
		String[] fieldsKey = {"CardID","UserName","Sex","BirthDay","Registry","Residence","PhoneNo","Email",
							"LinkMan","LinkManCall","OrgNo","OrgName","EmployTime","Source","SourceTypeName","SourceName1","Nature","AlipayNo",
							"WechatNo","BankNo"};
		String[] fieldsName = {"身份证号","姓名","性别","出生日期","原户籍地","现居住地","手机号码","邮箱",
							"紧急联系人","联系电话","企业编号","企业名称","入职时间","来源身份证号码","来源分类","来源","性质","支付宝",
							"微信账号","银行卡号"};
		Integer[] width = {20*256,10*256,10*256,15*256,30*256,15*256,15*256,30*256,
							10*256,15*256,10*256,30*256,10*256,20*256,10*256,20*256,10*256,15*256,
							15*256,20*256};
		/*StringBuffer titleBuffer = new StringBuffer();
		titleBuffer.append("姓名：").append(userMap.get("USERNAME") == null ? "无" : userMap.get("USERNAME").toString())
			.append("  电话：").append(phoneNo)
			.append("  银行名称：").append(userMap.get("BANKNAME") == null ? "无" : userMap.get("BANKNAME").toString())
			.append("  开户行：").append(userMap.get("ACCOUNTBANK") == null ? "无" : userMap.get("ACCOUNTBANK").toString())
			.append("  银行卡号：").append(userMap.get("ACCOUNT") == null ? "无" : userMap.get("ACCOUNT").toString());
		String titleName = titleBuffer.toString();*/
		String titleName = "员工资料导出";
		HSSFWorkbook workbook = ExportExcelUtil.list2Bytes(titleName, sheetName, fieldsKey, fieldsName, width, list);

		/*
		 * Boolean isSuccess = true; IExcelPrintByte excelPort =
		 * reportExportService.getExcelPort(); byte[] bytes; try { bytes =
		 * excelPort.excelPrintByte(reportCode, refNo); } catch
		 * (IExcelPrintByteExcelPrintByteApplicationServiceErrorFaultFaultMessage
		 * e1) { throw new
		 * WebserviceInvokeException(e1.getFaultInfo().getErrorMessage()); //
		 * e1.printStackTrace(); }
		 */

		OutputStream outputStream = null;
		try {
			// String realFileName = StringUtils.isEmpty(fileName) ? "未知文件名.xls"
			// : URLDecoder.decode(fileName,"utf-8")+".xls";
			String realFileName = StringUtils.isEmpty(fileName) ? "未知文件名.xls"
					: fileName + ".xls";
			realFileName = URLEncoder.encode(realFileName, "UTF-8");
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ realFileName + "\"");
			//response.addHeader("Content-Length", "" + bytes.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			outputStream = new BufferedOutputStream(response.getOutputStream());
			workbook.write(outputStream);
			//outputStream.write(bytes);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
			isSuccess = false;
			// throw new FileReadException("文件读取发生错误");
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		/*
		 * if (isSuccess) { OutputUtil.returnSuccess(response, isSuccess); }
		 */
	}
}
